package com.se.web;

import static com.se.web.Page.findPageById;

import java.util.ArrayList;
import java.util.List;

public class Breadcrumbs {

	private List<Link> links;

	private Breadcrumbs(List<Link> links) {
		this.links = links;
	}

	public static Breadcrumbs defaultBreadcrumbs() {
		List<Link> links = new ArrayList<Link>();
		links.add(new Link(Page.HOME.getTitle(), Page.HOME.getPath()));
		return new Breadcrumbs(links);
	}
	
	public static Breadcrumbs parseBreadcrumbs(String breadcrumbsFormat) {
		List<Link> links = new ArrayList<Link>();
		String[] breadcrumbFormats = breadcrumbsFormat.split(",");
		for (String breadcrumbFormat: breadcrumbFormats) {
			Link breadcrumb = parseBreadcrumb(breadcrumbFormat);
			if (breadcrumb != null) {
				links.add(breadcrumb);
			}
		}
		return new Breadcrumbs(links);
	}

	private static Link parseBreadcrumb(String breadcrumbFormat) {
		String[] bits = breadcrumbFormat.split(":");
		if (bits.length == 0) {
			return null;
		}
		Page page = findPageById(bits[0]);
		if (page == null) {
			return null;
		}
		StringBuilder titleBuilder = new StringBuilder(page.getTitle());
		StringBuilder urlBuilder = new StringBuilder(page.getPath());
		if (bits.length > 1) {
			String paramValue = bits[1];
			titleBuilder.append(" [" + paramValue + "]");
			urlBuilder.append("?" + page.getDefaultParam() + "=" + paramValue);
			// TODO: if (bits.length > 2)
		}
		return new Link(titleBuilder.toString(), urlBuilder.toString());
	}

	public List<Link> getLinks() {
		return links;
	}
}
